import axios from 'axios';

// API基础配置
const API_BASE_URL = 'http://101.33.122.140:8000';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 类型定义
export interface Homepage {
  id: number;
  title: string;
  content: string;
  version: number;
  is_published: boolean;
  is_active: boolean;
  created_by: number;
  created_at: string;
  updated_at: string | null;
}

export interface Category {
  id: number;
  name: string;
  description: string;
  slug: string;
  is_active: boolean;
  sort_order: number;
  created_at: string;
  updated_at: string | null;
}

export interface ProductImage {
  id: number;
  filename: string;
  original_filename: string;
  file_path: string;
  file_size: number;
  content_type: string;
  product_id: number | null;
  sort_order: number;
  created_at: string;
  updated_at: string | null;
}

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  original_price: number | null;
  category_id: number;
  is_active: boolean;
  sort_order: number;
  created_at: string;
  updated_at: string | null;
  images: ProductImage[];
  first_image_url?: string;
  tags: any[];
  detail: any;
}

// 修改密码接口类型
export interface PasswordChange {
  current_password: string;
  new_password: string;
}

// API类
export class ApiService {
  // 认证相关
  static async login(username: string, password: string): Promise<{ access_token: string; token_type: string }> {
    const formData = new URLSearchParams();
    formData.append('username', username);
    formData.append('password', password);

    const response = await fetch(`${API_BASE_URL}/api/v1/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formData,
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.detail || '登录失败');
    }

    return response.json();
  }

  // 修改密码
  static async changePassword(passwordData: PasswordChange): Promise<{ message: string }> {
    const response = await apiClient.post('/api/v1/auth/change-password', passwordData);
    return response.data;
  }

  // 首屏相关
  static async getPublishedHomepage(): Promise<Homepage> {
    const response = await apiClient.get('/api/v1/homepage/published');
    return response.data;
  }

  static async getHomepages(): Promise<Homepage[]> {
    const response = await apiClient.get('/api/v1/homepage/');
    return response.data;
  }

  static async createHomepage(data: Partial<Homepage>): Promise<Homepage> {
    const response = await apiClient.post('/api/v1/homepage/', data);
    return response.data;
  }

  static async updateHomepage(id: number, data: Partial<Homepage>): Promise<Homepage> {
    const response = await apiClient.put(`/api/v1/homepage/${id}`, data);
    return response.data;
  }

  static async deleteHomepage(id: number): Promise<void> {
    await apiClient.delete(`/api/v1/homepage/${id}`);
  }

  static async publishHomepage(id: number): Promise<{ message: string; homepage: Homepage }> {
    const response = await apiClient.post(`/api/v1/homepage/${id}/publish`);
    return response.data;
  }

  // 分类相关
  static async getCategories(): Promise<Category[]> {
    const response = await apiClient.get('/api/v1/categories/');
    return response.data;
  }

  static async getCategory(id: number): Promise<Category> {
    const response = await apiClient.get(`/api/v1/categories/${id}`);
    return response.data;
  }

  static async createCategory(data: Partial<Category>): Promise<Category> {
    const response = await apiClient.post('/api/v1/categories/', data);
    return response.data;
  }

  static async updateCategory(id: number, data: Partial<Category>): Promise<Category> {
    const response = await apiClient.put(`/api/v1/categories/${id}`, data);
    return response.data;
  }

  static async deleteCategory(id: number): Promise<void> {
    await apiClient.delete(`/api/v1/categories/${id}`);
  }

  // 商品相关
  static async getProducts(params?: {
    category_id?: number;
    name?: string;
    skip?: number;
    limit?: number;
  }): Promise<{items: Product[], total: number, page: number, page_size: number, total_pages: number}> {
    const response = await apiClient.get('/api/v1/products/', { params });
    return response.data;
  }

  static async getProduct(id: number): Promise<Product> {
    const response = await apiClient.get(`/api/v1/products/${id}`);
    return response.data;
  }

  static async createProduct(data: Partial<Product>): Promise<Product> {
    const response = await apiClient.post('/api/v1/products/', data);
    return response.data;
  }

  static async updateProduct(id: number, data: Partial<Product>): Promise<Product> {
    const response = await apiClient.put(`/api/v1/products/${id}`, data);
    return response.data;
  }

  static async deleteProduct(id: number): Promise<void> {
    await apiClient.delete(`/api/v1/products/${id}`);
  }

  static async addProductImage(productId: number, data: any): Promise<any> {
    const response = await apiClient.post(`/api/v1/products/${productId}/images`, data);
    return response.data;
  }

  static async getProductDetail(productId: number): Promise<any> {
    const response = await apiClient.get(`/api/v1/products/${productId}/detail`);
    return response.data;
  }

  static async updateProductDetail(productId: number, data: any): Promise<any> {
    const response = await apiClient.post(`/api/v1/products/${productId}/detail`, data);
    return response.data;
  }

  // 图片上传相关
  static async uploadImages(files: File[], productId?: number): Promise<ProductImage[]> {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    if (productId) {
      formData.append('product_id', productId.toString());
    }

    const response = await apiClient.post('/api/v1/upload/images/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  }

  static async getImages(productId?: number): Promise<ProductImage[]> {
    const params = productId ? { product_id: productId } : {};
    const response = await apiClient.get('/api/v1/upload/images/', { params });
    return response.data;
  }

  static getImageUrl(imageId: number): string {
    return `${API_BASE_URL}/api/v1/upload/images/${imageId}`;
  }

  static async deleteImage(imageId: number): Promise<void> {
    await apiClient.delete(`/api/v1/upload/images/${imageId}`);
  }

  static async associateImageWithProduct(imageId: number, productId: number): Promise<ProductImage> {
    const response = await apiClient.put(`/api/v1/upload/images/${imageId}/product?product_id=${productId}`);
    return response.data;
  }
}

export default ApiService; 